package com.hx.thread.airticket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author Minghua Chen
 * @date 2020-09-05 20:50
 */
public class CountDownLatchDemo {
    private static final Logger logger = LoggerFactory.getLogger(CountDownLatchDemo.class);
    static ExecutorService executorService = Executors.newFixedThreadPool(3);

    public static void main(String[] args) throws InterruptedException {
        CountDownLatchDemo downLatchDemo = new CountDownLatchDemo();
        logger.info("" + downLatchDemo.getPrices());
        executorService.shutdown();
    }

    private Set<Integer> getPrices() throws InterruptedException {
        Set<Integer> prices = Collections.synchronizedSet(new HashSet<>());
        CountDownLatch countDownLatch = new CountDownLatch(3);
        executorService.submit(new CountDownLatchDemo.Task(123, prices, countDownLatch));
        executorService.submit(new CountDownLatchDemo.Task(487, prices, countDownLatch));
        executorService.submit(new CountDownLatchDemo.Task(396, prices, countDownLatch));
        // 等待3s  如果3s内结束  无需等待3s
        countDownLatch.await(3, TimeUnit.SECONDS);
        return prices;
    }

    private class Task implements Runnable {
        Integer productId;
        Set<Integer> prices;
        CountDownLatch countDownLatch;

        public Task(Integer productId, Set<Integer> prices, CountDownLatch countDownLatch) {
            this.productId = productId;
            this.prices = prices;
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            int price = 0;
            try {
                Thread.sleep((long) (Math.random() * 4000));
                price = (int) (Math.random() * 4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            prices.add(price);
            countDownLatch.countDown();
        }
    }
}
